package com.bjqg.bjqg01.bjqg.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ajguan.library.EasyRefreshLayout;
import com.ajguan.library.LoadModel;
import com.bjqg.bjqg01.bjqg.R;
import com.bjqg.bjqg01.bjqg.adapter.HomeAdapter;
import com.bjqg.bjqg01.bjqg.adapter.PriceInQuiryAdapter;
import com.bjqg.bjqg01.bjqg.adapter.PriceInQuiryDrawerAdapter;
import com.bjqg.bjqg01.bjqg.bean.History;
import com.bjqg.bjqg01.bjqg.bean.SampleInfoBean;
import com.bjqg.bjqg01.bjqg.utils.Constant;
import com.bjqg.bjqg01.bjqg.utils.GreendaoUtils;
import com.bjqg.bjqg01.bjqg.utils.WebService;
import com.bjqg.greendao.HistoryDao;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Response;

/**
 * Created by bjqg01 on 2017/12/12.
 */

public class PriceInquiryActivity extends BaseActivity implements View.OnClickListener {

    private String yema = "1";
    private boolean isLoad = false;
    private int msgwhat = 0;
    private ImageView goback;
    private RecyclerView rvplu;
    private PriceInQuiryAdapter adapter;
    private String[] split1;
    private EditText etclmc;
    private EditText etjyxm;
    private TextView toptitle;
    private TextView tvsearch;
    private Button confirm;
    private Button reset;
    private DrawerLayout drawerlayout;
    private ArrayList<SampleInfoBean.DsBean> infoBeen;
    private Button btnUp;
    private Button btnDown;
    private RecyclerView menuListView;
    private PriceInQuiryDrawerAdapter draweradapter;
    private LinearLayout emptyContent;
    private List<History> historyList;
    private String cllbstr;
    private String jyxmstr;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_price_find);
        initView();
    }

    private void initView() {
        //top-title
        goback = (ImageView) findViewById(R.id.back);
        toptitle = (TextView) findViewById(R.id.tv_top_title_drawer);
        tvsearch = (TextView) findViewById(R.id.tv_search_top_drawer);
        //drawer
        drawerlayout = (DrawerLayout) findViewById(R.id.drawerlayout);
        btnUp = (Button) findViewById(R.id.sheng);
        btnDown = (Button) findViewById(R.id.jiang);
        menuListView = (RecyclerView) findViewById(R.id.menu_listView);
        etclmc = (EditText) findViewById(R.id.menu_clmc);
        etjyxm = (EditText) findViewById(R.id.menu_jyxm);

        emptyContent = (LinearLayout) findViewById(R.id.empty_content);
        confirm = (Button) findViewById(R.id.btn_confirm);
        reset = (Button) findViewById(R.id.btn_reset);

        //zhu
        rvplu = (RecyclerView) findViewById(R.id.rv_plu);

        toptitle.setText("价格查询");
        goback.setOnClickListener(this);
        tvsearch.setOnClickListener(this);

        confirm.setOnClickListener(this);
        reset.setOnClickListener(this);
        btnUp.setOnClickListener(this);
        btnDown.setOnClickListener(this);
        emptyContent.setOnClickListener(this);

        initData();
//        getindata();

    }

    private void pullUpLoading(final PriceInQuiryAdapter adapter) {
        final EasyRefreshLayout easyRefreshLayout = (EasyRefreshLayout) findViewById(R.id.refresh_price_layout);
        easyRefreshLayout.setLoadMoreModel(LoadModel.COMMON_MODEL);
        easyRefreshLayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
            @Override
            public void onLoadMore() {

                if (isLoad){
                    Toast.makeText(PriceInquiryActivity.this,"没有更多数据",Toast.LENGTH_SHORT).show();
                    easyRefreshLayout.loadMoreComplete();
//                    return;
                } else {
                    msgwhat = 1;
                    int intyema = Integer.parseInt(yema);
                    yema = (intyema += 1) + "";
                    getokgo(yema);
                    easyRefreshLayout.loadMoreComplete();
                }
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        easyRefreshLayout.loadMoreComplete(new EasyRefreshLayout.Event() {
//                            @Override
//                            public void complete() {
//                                Toast.makeText(PriceInquiryActivity.this,"没有更多数据",Toast.LENGTH_SHORT).show();
//                            }
//                        }, 500);
//                    }
//                }, 2000);
            }

            @Override
            public void onRefreshing() {
                yema = "1";
                msgwhat = 0;
                getokgo(yema);
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
                        easyRefreshLayout.refreshComplete();
//                    }
//                }, 1000);

            }
        });

    }
    private Handler uiHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            adapter.notifyDataSetChanged();
        }
    };

    private void getindata() {
        new Thread(){
            @Override
            public void run() {
                super.run();

                final String webService = WebService.getInstance().getWebService(Constant.BASEURL, "Constant.NAMESPACE", "Constant.GETALLSTUDENTINFO2");
                Gson gson = new Gson();
                final SampleInfoBean sampleInfoBean = gson.fromJson(webService, SampleInfoBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LinearLayoutManager layoutManager = new LinearLayoutManager(PriceInquiryActivity.this);
                        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                        rvplu.setLayoutManager(layoutManager);

                        adapter = new PriceInQuiryAdapter(R.layout.item_price_find, sampleInfoBean.getDs());

                        rvplu.setAdapter(adapter);
//                        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                            @Override
//                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                                Toast.makeText(getApplicationContext(),""+position,Toast.LENGTH_SHORT).show();
//                            }
//                        });
                    }
                });
            }
        }.start();
    }

    private void initData() {

        getokgo(yema);

        showDrawerListView();
//        Observable.create(new ObservableOnSubscribe<SampleInfoBean>() {
//            @Override
//            public void subscribe(@NonNull ObservableEmitter<SampleInfoBean> e) throws Exception {
//                getokgo();
//
////                String webService = WebService.getInstance().getWebService(Constant.BASEURL, Constant.NAMESPACE, Constant.GETALLSTUDENTINFO2);
//                Gson gson = new Gson();
////                SampleInfoBean sampleInfoBean = gson.fromJson(str[0], SampleInfoBean.class);
////                e.onNext(sampleInfoBean);
////                Log.e("subscribe: ", "asdfghjklqwertyuiop[zxcvbnm,."+Thread.currentThread().getName().toString());
//            }
//        })
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<SampleInfoBean>() {
//                    @Override
//                    public void accept(SampleInfoBean o) throws Exception {
////                        Log.e("subscribe: ", Thread.currentThread().getName().toString());
//                        //更新UI
//                        showListView(o);
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(@NonNull Throwable throwable) throws Exception {
//                        Log.e("----------error","失败：--------------------rxjava" + throwable.getMessage() + "\n");
//                    }
//                });
    }

    private void showDrawerListView() {
        HistoryDao historyDao = GreendaoUtils.getDaoSession(getApplicationContext(), Constant.HISTORYDBNAME).getHistoryDao();
        historyList = historyDao.queryBuilder()
                .where(HistoryDao.Properties.Type.eq(Constant.PRICEHISTORYDBTYPE))
                .limit(10).orderDesc(HistoryDao.Properties.Date).build().list();

        LinearLayoutManager layoutManager = new LinearLayoutManager(PriceInquiryActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        menuListView.setLayoutManager(layoutManager);

        draweradapter = new PriceInQuiryDrawerAdapter(R.layout.item_price_find_drawer, historyList);
        if (historyList.size()>0){
            emptyContent.setVisibility(View.VISIBLE);
        }else {
            emptyContent.setVisibility(View.GONE);
        }
        menuListView.setAdapter(draweradapter);

        draweradapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String content = historyList.get(position).getContent();
                boolean contains = content.contains("&");
                if (contains){
                    String[] split = content.split("&");
                    etclmc.setText(split[0]);
                    etjyxm.setText(split[1]);
                }else {
                    etclmc.setText(content);
                    etjyxm.setText("");
                }

            }
        });

    }

    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    SampleInfoBean refreshinfo = msg.getData().getParcelable("sampleinfobean");
                    yema = refreshinfo.getPageNum().toString();
                    int size = refreshinfo.getDs().size();
                    if (size < 15){
                        isLoad=true;
                    }else {
                        isLoad = false;
                    }

                    showListView(refreshinfo);
                    break;
                case 1:
                    SampleInfoBean loadinfo = msg.getData().getParcelable("sampleinfobean");
                    yema = loadinfo.getPageNum().toString();
                    List<SampleInfoBean.DsBean> ds = loadinfo.getDs();
                    if (ds.size() < 15){
                        isLoad = true;
                    }
                    infoBeen.addAll(ds);
                    adapter.setNewData(infoBeen);
//                    rvplu.notify();
                    Log.e("----------handler","失败：------------------------okgo"+loadinfo.toString());
                    break;

                case 2:
                    ArrayList<History> historyList1 = msg.getData().getParcelableArrayList("historyList1");
                    draweradapter.setNewData(historyList1);
                    if (historyList1.size()>0){
                        emptyContent.setVisibility(View.VISIBLE);
                    }else {
                        emptyContent.setVisibility(View.GONE);
                    }
                    break;
                case 3:
                    draweradapter.setNewData(historyList);
                    break;
            }

        }
    };

    private void getokgo(String pagenum) {

//        String sqlwere="";
//        String sqlwhere= "jyxm=";
        String url = getUrl(pagenum);
        Log.d("abcde", "getokgo: "+url);
//        Log.e("pagenum: ", pagenum.toString());
//        String jyxmcode = URLEncoder.encode(jyxmstr);
//        final String[] strreturn = {""};
//        Log.e("getokgo:encode ", encode);
        OkGo.<String>get(url)
//        OkGo.<String>get("http://www.tjzj21erp.com:8098/Service1.asmx/SelectjycsDj?yema="+yema+"&sqlwhere=")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
//                        if (sampleInfoBean.getDs().size()==0){
//                            int i=0;
                            Log.e("----------error","失败：------------------------okgo");
//                        }
                        String str= "<string xmlns=\"http://tempuri.org/\">";
                        String strend="</string>";
                        String strerror = "{\"ds\":{}}";
                        String[] split = response.body().toString().split(str);
//                        Log.e("onSuccess: ", ""+split[1]);
                        split1 = split[1].split(strend);
//                        if (split1[0].contains("\\")){
//                            split1[0] = split1[0].replace("\\", "/");
//                        }
//                        Log.e("----------error","失败：------------------------okgo"+split1[0]);
//                        strreturn[0] = split1[0];
                        if (strerror.equals(split1[0])){
                            Toast.makeText(PriceInquiryActivity.this,"您所查询的结果不存在",Toast.LENGTH_SHORT).show();
                            etclmc.setText("");
                            etjyxm.setText("");
                        }else {
                            Gson gson = new Gson();
                            SampleInfoBean sampleInfoBean = gson.fromJson(split1[0], SampleInfoBean.class);

                            Message message = Message.obtain();
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("sampleinfobean", sampleInfoBean);
                            if (msgwhat == 0) {
                                message.what = 0;
                            } else {
                                message.what = 1;
                            }
                            message.setData(bundle);
                            myHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<String> response) {
                        super.onError(response);
//                        Log.e("----------error","失败：------------------------okgo");
                        Toast.makeText(PriceInquiryActivity.this,"服务器正忙，请稍后再试!",Toast.LENGTH_SHORT).show();
                    }
                });

    }

    @android.support.annotation.NonNull
    private String getUrl(String pagenum) {
        StringBuffer sb = new StringBuffer();
        String cllbstr = etclmc.getText().toString().trim();
        String jyxmstr = etjyxm.getText().toString().trim();
        if (cllbstr!=null&&cllbstr!=""&&!cllbstr.equals("")){
            String cllbcode = URLEncoder.encode(cllbstr);
            sb.append("clmc="+cllbcode);
        }
        if (jyxmstr!=null&&jyxmstr!=""&&!jyxmstr.equals("")){
            if (sb.toString().length()!=0)sb.append("&");
            String jyxmcode = URLEncoder.encode(jyxmstr);
            sb.append("jyxm="+jyxmcode);
        }
        String url = Constant.BASEURL+Constant.SELECTJYCSDJ+"?yema="
                + pagenum + "&sqlwhere=" + sb.toString();
        Log.e("----------error","失败：------------------------"+url);
        return url;
    }

    private void showListView(SampleInfoBean o) {
        infoBeen = new ArrayList<>();
        infoBeen.addAll(o.getDs());
        LinearLayoutManager layoutManager = new LinearLayoutManager(PriceInquiryActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvplu.setLayoutManager(layoutManager);
        adapter = new PriceInQuiryAdapter(R.layout.item_price_find, infoBeen);
        rvplu.setAdapter(adapter);

        pullUpLoading(adapter);
//        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Toast.makeText(getApplicationContext(),""+position,Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    @Override
    public void onBackPressed() {
        if (drawerlayout.isDrawerOpen(Gravity.RIGHT)){
//            Toast.makeText(PriceInquiryActivity.this,"返回",Toast.LENGTH_SHORT).show();
            drawerlayout.closeDrawer(Gravity.RIGHT);
        }else {
            super.onBackPressed();
        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.tv_search_top_drawer:
                drawerlayout.openDrawer(Gravity.RIGHT);
                break;
            case R.id.btn_confirm:
                cllbstr = etclmc.getText().toString().trim();
                jyxmstr = etjyxm.getText().toString().trim();
                if (cllbstr.contains("&")||jyxmstr.contains("&")){
                    Toast.makeText(PriceInquiryActivity.this,"搜索内容包含敏感符号",Toast.LENGTH_SHORT).show();
                    return;
                }
                drawerlayout.closeDrawer(Gravity.RIGHT);
//                if (cllbstr==null||cllbstr.equals("")&&jyxmstr==null||jyxmstr.equals("")){
//                    return;
//                }

                yema = "1";
                msgwhat = 0;
                getokgo(yema);

                sendhistory();

                break;
            case R.id.btn_reset:
                etclmc.setText("");
                etjyxm.setText("");
                break;
            case R.id.sheng:

                break;
            case R.id.jiang:

                break;
            case R.id.empty_content:
//                Toast.makeText(PriceInquiryActivity.this,"123",Toast.LENGTH_SHORT).show();
                deleteHistory();
                break;
        }
    }

    private void deleteHistory() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                HistoryDao historyDao = GreendaoUtils.getDaoSession(getApplicationContext(), Constant.HISTORYDBNAME).getHistoryDao();
                for (int i = 0; i < historyList.size(); i++) {
                    History unique = historyDao.queryBuilder()
                            .where(HistoryDao.Properties.Id.eq(historyList.get(i).getId())).build().unique();
                    historyDao.delete(unique);
                }
                historyList.clear();
                Message message = Message.obtain();
//                message.what = 3;
////        myHandler.sendMessage(message);
//                myHandler.sendEmptyMessage(message.what);
                Bundle bundle = new Bundle();
//                bundle.putParcelable("historyList1",historyList1);
                bundle.putParcelableArrayList("historyList1",(ArrayList<History>) historyList);
                message.what = 2;
                message.setData(bundle);
                myHandler.sendMessage(message);
            }
        }.start();

    }

    private void sendhistory() {
        if (cllbstr.equals("")&&jyxmstr.equals("")){
            return;
        }
        new Thread(){
            @Override
            public void run() {
                super.run();

                long minid = 0;

                HistoryDao historyDao = GreendaoUtils.getDaoSession(getApplicationContext(), Constant.HISTORYDBNAME).getHistoryDao();
                historyList = historyDao.queryBuilder()
                        .where(HistoryDao.Properties.Type.eq(Constant.PRICEHISTORYDBTYPE)).limit(10).build().list();

                if (historyList.size()==10) {
                    ArrayList<Long> longs = new ArrayList<>();
                    for (int i = 0; i < historyList.size(); i++) {
                        longs.add(historyList.get(i).getDate());
                    }

                    Long min = Collections.min(longs);
                    for (int i = 0; i < historyList.size(); i++) {
                        History his = historyList.get(i);
                        if (min == his.getDate()) {
                            minid = his.getId();
                        }
                    }
                    History unique = historyDao.queryBuilder().where(HistoryDao.Properties.Id.eq(minid)).build().unique();
                    historyDao.delete(unique);
                }

                History history = getHistory();
                if (history==null)return;
                historyDao.insert(history);

                HistoryDao historyDao1 = GreendaoUtils.getDaoSession(getApplicationContext(), Constant.HISTORYDBNAME).getHistoryDao();
                historyList = historyDao1.queryBuilder()
                        .where(HistoryDao.Properties.Type.eq(Constant.PRICEHISTORYDBTYPE))
                        .limit(10).orderDesc(HistoryDao.Properties.Date).build().list();
                for (int i = 0; i < historyList.size(); i++) {

                    Log.e("run: ", historyList.get(i).getContent());
                }
//                draweradapter.setNewData(historyList1);
                Message message = Message.obtain();
                Bundle bundle = new Bundle();
//                bundle.putParcelable("historyList1",historyList1);
                bundle.putParcelableArrayList("historyList1",(ArrayList<History>) historyList);
                message.what = 2;
                message.setData(bundle);
                myHandler.sendMessage(message);

            }
        }.start();
    }

    @android.support.annotation.NonNull
    private History getHistory() {
        StringBuffer sb = new StringBuffer();
        cllbstr = etclmc.getText().toString().trim();
        jyxmstr = etjyxm.getText().toString().trim();
        if (cllbstr.contains("&")||jyxmstr.contains("&")){
            Toast.makeText(PriceInquiryActivity.this,"搜索内容包含敏感符号",Toast.LENGTH_SHORT).show();
            return null;
        }
        long timeMillis = System.currentTimeMillis();
        if (cllbstr !=null&& cllbstr !=""&&!cllbstr.equals("")){
            sb.append(cllbstr);
        }
        if (jyxmstr !=null&& jyxmstr !=""&&!jyxmstr.equals("")){
//            if (sb.toString().length()!=0)sb.append("&");
            sb.append("&"+ jyxmstr);
        }
        return new History(null, Constant.PRICEHISTORYDBTYPE, timeMillis, sb.toString());
    }
}
